import { useUserStore } from '@/stores/user.js'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from "@/router/index.js";

// 创建 Axios 实例
const baseURL = 'api'
const instance = axios.create({
    baseURL,
    timeout: 10000
})
// 请求拦截器
instance.interceptors.request.use(config => {
    const userStore = useUserStore() // 正确调用 useUserStore
    const token = userStore.token // 获取 token
    if (config.url.includes('login') || config.url.includes('register') || config.url.includes('captcha')) {
        return config
    }
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }

    return config
}, error => {
    return Promise.reject(error)
})

instance.interceptors.response.use(
    (res) => {
        if (res.data.code === 500) {
            ElMessage.error(res.data.msg || '服务异常，请稍后再试')
            console.log('异常执行了')
            return Promise.reject(res.data)
        } else if (res.data.code === 401) {
            ElMessage.error(res.data. msg || '登录失效，请重新登录')
            router.push('/') // 跳转到登录页面
            return Promise.reject(res.data)
        }
        return res
    }
)


export default instance
export { baseURL }
